#include <os/task.h>
#include <os/string.h>
#include <os/kernel.h>
#include <type.h>

#define TASKNUM_LOC 0x502001fa
#define TASK5 1

uint64_t load_task_img(
#ifdef TASK4
    char *name
#else
    int taskid
#endif
)
{
    /**
     * TODO:
     * 1. [p1-task3] load task from image via task id, and return its entrypoint
     * 2. [p1-task4] load task via task name, thus the arg should be 'char *taskname'
     */
    int i = 1;
    // #ifdef TASK4
    //     int taskid = 0;
    //     for (i = 1; i <= 5; i++)
    //     {
    //         if (!strcmp(tasks[i].name, name))
    //         {
    //             bios_putchar(i + '0');
    //             bios_putchar('\n');
    //             taskid = i;
    //             break;
    //         }
    //     }
    // #endif
    char *tasknum = TASKNUM_LOC;
    /*if (i > *tasknum || taskid > *tasknum)
        return 0;*/
    unsigned blockid = tasks[taskid].start_block;
    unsigned blocknm = tasks[taskid].num_block;
    // unsigned ret_address = TASK_MEM_BASE + (taskid - 1) * TASK_SIZE;
    // unsigned mem_address = ret_address - tasks[taskid].offset;
    unsigned mem_address = TASK_MEM_BASE + (taskid - 1) * TASK_SIZE;
    unsigned ret_address = mem_address + tasks[taskid].offset;
    bios_sdread(mem_address, blocknm, blockid);
    return ret_address;
}

uint64_t load_address(int taskid)
{
    // int i = 1;
    unsigned mem_address = TASK_MEM_BASE + (taskid - 1) * TASK_SIZE;
    unsigned ret_address = mem_address + tasks[taskid].offset;
    // unsigned mem_address = ret_address - tasks[taskid].offset;
    // unsigned ret_address = TASK_MEM_BASE + (taskid - 1) * TASK_SIZE;
    return ret_address;
}